﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace REVISIONMAX30.Controls
{
    public partial class MySQLItemList : UserControl
    {
        public MySQLItemList()
        {
            InitializeComponent();
        }

        public UIHandler uiHandler { get; set; }
        public DataObjects.Group group { get; set; }

        public void Initzialize(UIHandler pUIHandler, DataObjects.Group pParentObject)
        {
            this.uiHandler = pUIHandler;
            this.group = pParentObject;
            this.UpdateViewer();
        }

        public List<Guid> SelectedGuidList
        {
            get
            {
                return this.lvSQLItems.SelectedItems.Cast<ListViewItem>().Select(t => t.Tag).Cast<Guid>().ToList();
            }
        }

        public List<DataObjects.SQLItem> SelectedSQLItemList
        {
            get
            {
                return this.group.SQLItemList.Where(t => SelectedGuidList.Contains(t.DataObjectGUID)).ToList();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            group.SQLItemList.RemoveAll(t => this.SelectedGuidList.Contains(t.DataObjectGUID));

            this.UpdateViewer();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            this.Edit();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {

            //StringBuilder builder = new StringBuilder();
            //foreach (ListViewItem item in this.lvSQLItems.SelectedItems)
            //{
            //    SortedList<int, string> connectionStringIdValueList = Common.GetConnectionStringIdValueList(this._parent);
            //    try
            //    {
            //        SQLItem sQLItemById = Common.GetSQLItemById((int)item.Tag, this._parent);
            //        if (connectionStringIdValueList.ContainsKey(sQLItemById.connectionstringid))
            //        {
            //            string connectionString = connectionStringIdValueList[sQLItemById.connectionstringid];
            //            MySqlConnectionStringBuilder builder2 = new MySqlConnectionStringBuilder(connectionString);
            //            using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //            {
            //                string str2;
            //                connection.Open();
            //                REVISIONMAX30.Log pErrorLog = new REVISIONMAX30.Log("", this._parent, connection);
            //                REVISIONMAX30.Log pOutLog = new REVISIONMAX30.Log("", this._parent, connection);
            //                if (sQLItemById.sourcetype == "sqlfile")
            //                {
            //                    str2 = Common.ExecuteBatch(builder2.UserID, builder2.Password, builder2.Database, sQLItemById.source, pErrorLog, pOutLog);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    sQLItemById.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(sQLItemById.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                }
            //                else if (sQLItemById.sourcetype == "sourcetext")
            //                {
            //                    string tempFileName = Path.GetTempFileName();
            //                    File.WriteAllText(tempFileName, sQLItemById.source);
            //                    str2 = Common.ExecuteBatch(builder2.UserID, builder2.Password, builder2.Database, tempFileName, pErrorLog, pOutLog);
            //                    File.Delete(tempFileName);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    sQLItemById.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(sQLItemById.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                }
            //                if (!pErrorLog.value.IsEmpty())
            //                {
            //                    pErrorLog.SaveOrUpdate();
            //                }
            //                if (!pOutLog.value.IsEmpty())
            //                {
            //                    pOutLog.SaveOrUpdate();
            //                }
            //            }
            //        }
            //    }
            //    catch (Exception exception)
            //    {
            //        builder.AppendLine(string.Format("Error: {0}", exception.Message));
            //    }
            //    if (builder.Length > 0)
            //    {
            //        MessageBox.Show(builder.ToString());
            //    }
            //}
            //this.UpdateViewer();
        }

        private void btnExecuteViaADODB_Click(object sender, EventArgs e)
        {
            //StringBuilder builder = new StringBuilder();
            //foreach (ListViewItem item in this.lvSQLItems.SelectedItems)
            //{
            //    SortedList<int, string> connectionStringIdValueList = Common.GetConnectionStringIdValueList(this._parent);
            //    try
            //    {
            //        SQLItem sQLItemById = Common.GetSQLItemById((int)item.Tag, this._parent);
            //        if (connectionStringIdValueList.ContainsKey(sQLItemById.connectionstringid))
            //        {
            //            string connectionString = connectionStringIdValueList[sQLItemById.connectionstringid];
            //            MySqlConnectionStringBuilder builder2 = new MySqlConnectionStringBuilder(connectionString);
            //            using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //            {
            //                string str2;
            //                connection.Open();
            //                REVISIONMAX30.Log pErrorLog = new REVISIONMAX30.Log("", this._parent, connection);
            //                REVISIONMAX30.Log pOutLog = new REVISIONMAX30.Log("", this._parent, connection);
            //                if (sQLItemById.sourcetype == "sqlfile")
            //                {
            //                    str2 = Common.ExecuteViaMYSQL(sQLItemById.source, builder2.ConnectionString, pErrorLog, pOutLog);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    sQLItemById.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(sQLItemById.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                }
            //                else if (sQLItemById.sourcetype == "sourcetext")
            //                {
            //                    string tempFileName = Path.GetTempFileName();
            //                    File.WriteAllText(tempFileName, sQLItemById.source);
            //                    str2 = Common.ExecuteViaMYSQL(tempFileName, builder2.ConnectionString, pErrorLog, pOutLog);
            //                    File.Delete(tempFileName);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    sQLItemById.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(sQLItemById.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                }
            //                if (!pErrorLog.value.IsEmpty())
            //                {
            //                    pErrorLog.SaveOrUpdate();
            //                }
            //                if (!pOutLog.value.IsEmpty())
            //                {
            //                    pOutLog.SaveOrUpdate();
            //                }
            //            }
            //        }
            //    }
            //    catch (Exception exception)
            //    {
            //        builder.AppendLine(string.Format("Error: {0}", exception.Message));
            //    }
            //    if (builder.Length > 0)
            //    {
            //        MessageBox.Show(builder.ToString());
            //    }
            //}
            //this.UpdateViewer();
        }

        private void btnExpire_Click(object sender, EventArgs e)
        {
            foreach (var tSQLItem in SelectedSQLItemList)
            {
                if (tSQLItem.Expired == null)
                    tSQLItem.Expired = DateTime.Now;
                else
                    tSQLItem.Expired = null;
            }

            this.UpdateViewer();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {

            this.uiHandler.ViewSQLItem(new DataObjects.SQLItem(), this.group);

            this.UpdateViewer();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.UpdateViewer();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            foreach (var tSQLItem in SelectedSQLItemList)
            {
                tSQLItem.Executed = null;
            }

            this.UpdateViewer();
        }

        private void btnSetConnectionString_Click(object sender, EventArgs e)
        {
            var tSelectedText = this.cboConnectionStrings.SelectedText;

            if (tSelectedText.IsEmpty())
            {
                MessageBox.Show("Please select Connection String to Set.");
            }
            else if (this.group.ConnectionStringList.Exists(t => t.Name.Equals(tSelectedText, StringComparison.CurrentCultureIgnoreCase)))
            {
                MessageBox.Show(string.Format("Connection String {0} is not valid.", tSelectedText));
            }
            else
            {
                var tConnectionString = this.group.ConnectionStringList.Where(t => t.Name.Equals(tSelectedText, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                foreach (var tSQLItem in SelectedSQLItemList)
                {
                    tSQLItem.SelectedConnectionStringGUID = tConnectionString.DataObjectGUID;
                }

                this.UpdateViewer();

            }
        }

        private void btnSetRevisionAndIndex_Click(object sender, EventArgs e)
        {
            var tRevision = this.txtRevision.Text.IntValueOrZero();
            var tIndex = this.txtIndex.Text.IntValueOrZero();
            if ((tIndex == 0) || this.txtRevision.Text.IsEmpty())
            {
                MessageBox.Show("revision must be specified and index must be more then 0.");
            }

            else
            {
                foreach (var tSQLItem in SelectedSQLItemList)
                {
                    tSQLItem.Revision = tRevision;
                    tSQLItem.ExecutionOrderIndex = tIndex;
                }

                this.UpdateViewer();

            }

        }

        private void btnShowExpired_Click(object sender, EventArgs e)
        {
            this.UpdateViewer();
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            foreach (var tSQLItem in SelectedSQLItemList)
            {
                if (tSQLItem.SourceType == "SQLFILE")
                {
                    System.Diagnostics.Process.Start(tSQLItem.Source);
                }

            }
        }

        private void Edit()
        {
            if (this.lvSQLItems.SelectedItems.Count > 0)
            {
                var tSelectedGUID = (Guid)this.lvSQLItems.SelectedItems[0].Tag;
                this.uiHandler.ViewSQLItem(this.group.SQLItemList.Where(t => t.DataObjectGUID == tSelectedGUID).First(), this.group);
                this.UpdateViewer();
            }
        }

        private void lvSQLItems_DoubleClick(object sender, EventArgs e)
        {
            this.Edit();
        }

        public void UpdateViewer()
        {
            //this.cboConnectionStrings.Items.Clear();
            //foreach (DataRow row in Common.GetConnectionStringDataTable(this._parent.id).Rows)
            //{
            //    this.cboConnectionStrings.Items.Add(row["name"].StringValueOrEmpty());
            //}
            //this.lvSQLItems.Items.Clear();
            //SortedList<int, string> connectionStringIdNameList = Common.GetConnectionStringIdNameList(this._parent);
            //using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //{
            //    connection.Open();
            //    using (SQLiteCommand command = connection.CreateCommand())
            //    {
            //        command.CommandText = string.Format("select * from sqlitems  where  `parentid` = {0} {1} order by `connectionstringid`,  cast(`revision` as int), `index`", this._parent.id, !this.btnShowExpired.Checked ? " AND `expired` is null " : "");
            //        SQLiteDataReader reader = command.ExecuteReader();
            //        while (reader.Read())
            //        {
            //            SQLItem item = new SQLItem(reader, this._parent);
            //            ListViewItem item2 = this.lvSQLItems.Items.Add(item.index.ToString());
            //            item2.Tag = item.id;

            //            if (item.sourcetype == "sqlfile")
            //            {
            //                if (File.Exists(item.source))
            //                {
            //                    item2.SubItems.Add(Path.GetFileNameWithoutExtension(item.source));
            //                }
            //                else
            //                {
            //                    item2.SubItems.Add(item.source);
            //                }
            //            }
            //            else
            //            {
            //                item2.SubItems.Add("[sql text]" + item.source);
            //            }

            //            item2.SubItems.Add(item.sourcetype);
            //            item2.SubItems.Add(item.revision.StringValueOrEmpty());
            //            if (connectionStringIdNameList.ContainsKey(item.connectionstringid))
            //            {
            //                item2.SubItems.Add(connectionStringIdNameList[item.connectionstringid]);
            //            }
            //            else
            //            {
            //                item2.SubItems.Add("");
            //            }
            //            item2.SubItems.Add(item.created.StringValueOrEmpty());
            //            item2.SubItems.Add(item.updated.StringValueOrEmpty());
            //            item2.SubItems.Add(item.executed.StringValueOrEmpty());
            //            if (item.expired.HasValue)
            //            {
            //                item2.ForeColor = Color.Red;
            //            }
            //            else if (item.executed.HasValue)
            //            {
            //                item2.ForeColor = Color.DarkGreen;
            //            }
            //            else
            //            {
            //                item2.ForeColor = Color.DarkOrange;
            //            }
            //        }
            //    }
            //}
            //if (this.lvSQLItems.Items.Count > 0)
            //{
            //    foreach (ColumnHeader header in this.lvSQLItems.Columns)
            //    {
            //        header.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            //    }
            //}
        }

        private void btnExecuteViaMySQLConnector_Click(object sender, EventArgs e)
        {

        }

        private void btnExecuteSelectedViaBatch_Click(object sender, EventArgs e)
        {

        }

        private void lvSQLItems_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}
